package com.foo.mynbapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends AppCompatActivity {

    private int progress = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar);
        //进度条
        ProgressBar pb3 = findViewById(R.id.pb3);
        Button btnAdd = findViewById(R.id.btn_add);

        //为按钮添加事件
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int current = pb3.getProgress();
                int max = pb3.getMax();
                if (current < max) {
                    pb3.setProgress(current + 10);
                } else {
                    //当进度为100时 无法点击按钮
                    btnAdd.setEnabled(false);
                }
            }
        });

        ProgressBar pb4 = findViewById(R.id.pb4);

        Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    //将线程产生的随机数设置为进度条哦，
                    pb4.setProgress(progress);
                } else {
                    //当msg不为1时
                    Toast.makeText(ProgressBarActivity.this, "加载完成",
                            Toast.LENGTH_SHORT).show();
                    pb4.setVisibility(View.GONE);
                }
                return true;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    //随机增加进度
                    progress += Math.random() * 10;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    //判断
                    if (progress <= 100) {
                        msg.what = 1;
                        handler.sendMessage(msg);
                    } else {
                        msg.what = -1;
                        handler.sendMessage(msg);
                        //退出线程
                        break;
                    }
                }
            }
        }).start();
    }
}